package com.resume.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.resume.domain.Province;
import com.resume.domain.ProvinceQuery;
import com.resume.domain.ProvinceUpdate;
import com.resume.mapper.ProvinceMapper;
import com.resume.service.ProvinceService;
import com.resume.utils.RedisUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Author: 梁云亮
 * @Date: 2021/7/19 17:08
 * @Describe:
 */
@Service
public class ProvinceServinceImpl extends ServiceImpl<ProvinceMapper, Province> implements ProvinceService {

    @Resource
    private RedisUtil<Province> redisUtil;

    @Override
    public List<Province> listProvince(ProvinceQuery provinceQuery) {
        List<Province> provinceList ;
        if (redisUtil.exists("list_province")) {
//            如果缓存中存在，直接从缓存中取
            provinceList = redisUtil.lGet("list_province",0,-1);
        } else {
            //如果不存在
            QueryWrapper<Province> queryMapper = new QueryWrapper<>();
            queryMapper.select("id", "name", "area", "priority", "status");
            if (provinceQuery.getArea() != null) {
                queryMapper.like("area", provinceQuery.getArea());
            }
            if (provinceQuery.getStatus() != null) {
                queryMapper.eq("status", provinceQuery.getStatus());
            }
            //没有必要排序，因为最终数据需要存在Redis的hash中，而Redis中hash中的元素无序的
            queryMapper.orderByAsc("area");
            queryMapper.orderByDesc("priority");

            provinceList = baseMapper.selectList(queryMapper);
//            将查询出来的数据放到缓存中
            redisUtil.lSets("list_province", provinceList);
        }
        return provinceList;
    }

    @Override
    public boolean modifyProvince(ProvinceUpdate provinceUpdate) {
        Province province = new Province();
        BeanUtils.copyProperties(provinceUpdate, province);
        int updateRes = baseMapper.updateById(province);
        return updateRes == 1 ? true : false;
    }
}
